package simulaco.dao;

import gminet.infra.dao.DataAccessObject;
import gminet.infra.db.TransactionException;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import simulaco.dto.Orgao;
import simulaco.dto.Situacao;

public class OrgaoDAO extends DataAccessObject {

    public static Orgao findByPK(int orgaoId, Connection conn) throws TransactionException {

        StringBuffer sbSql = new StringBuffer();
        sbSql.append("SELECT A.CD_ORGAO     CD_ORGAO     ");
        sbSql.append("     , A.TX_NOME      TX_NOME      ");
        sbSql.append("     , A.ID_SITUACAO  ID_SITUACAO  ");
        sbSql.append("     , A.TS_CADASTRO  TS_CADASTRO  ");
        sbSql.append("  FROM ORGAO        A ");
        sbSql.append(" WHERE A.CD_ORGAO = ? ");

        Orgao orgao = null;
        try {
            PreparedStatement ps = conn.prepareStatement(sbSql.toString());
            setInt(ps, 1, orgaoId);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                orgao = fromResultSet(rs);
            }
            close(ps);
        } catch (SQLException sqle) {
            throw new TransactionException("OrgaoDAO.findByPK (" + sqle.getMessage() + ")");
        }
        return orgao;
    }

    public static List<Orgao> findAll(Connection conn) throws TransactionException {

        StringBuffer sbSql = new StringBuffer();
        sbSql.append("SELECT A.CD_ORGAO     CD_ORGAO     ");
        sbSql.append("     , A.TX_NOME      TX_NOME      ");
        sbSql.append("     , A.ID_SITUACAO  ID_SITUACAO  ");
        sbSql.append("     , A.TS_CADASTRO  TS_CADASTRO  ");
        sbSql.append("  FROM ORGAO  A ");
        sbSql.append(" ORDER BY A.TX_NOME ");
        List<Orgao> orgaosList = new ArrayList<Orgao>(100);
        try {
            PreparedStatement ps = conn.prepareStatement(sbSql.toString());
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                Orgao orgao = fromResultSet(rs);
                orgaosList.add(orgao);
            }
            close(rs);
        } catch (SQLException sqle) {
            throw new TransactionException("OrgaoDAO.findAll (" + sqle.getMessage() + ")");
        }
        return orgaosList;
    }

    public static List<Orgao> findByFilter(OrgaoFilter filter, Connection conn) throws TransactionException {

        StringBuffer sbSql = new StringBuffer();
        sbSql.append("SELECT A.CD_ORGAO     CD_ORGAO     ");
        sbSql.append("     , A.TX_NOME      TX_NOME      ");
        sbSql.append("     , A.ID_SITUACAO  ID_SITUACAO  ");
        sbSql.append("     , A.TS_CADASTRO  TS_CADASTRO  ");
        sbSql.append("  FROM ORGAO  A ");
        sbSql.append(" WHERE 1 = 1 ");
        if (filter.hasPrimeiroDigito()) {
            String strLetra = filter.getPrimeiroDigito().toLowerCase();
            if (strLetra.equalsIgnoreCase("0")) {
                sbSql.append(" AND LEFT(A.TX_NOME, 1) < 'A'");
            } else {
                sbSql.append(" AND LOWER(A.TX_NOME) like '" + strLetra + "%' ");
            }
        }
        if (filter.hasNome()) {
            String strName = filter.getNome().toLowerCase();
            sbSql.append(" AND LOWER(A.TX_NOME) like '%" + strName + "%' ");
        }
        if (filter.hasCodigoSituacao()) {
            sbSql.append(" AND A.ID_SITUACAO = ? ");
        }
        sbSql.append(" ORDER BY A.TX_NOME   ");
        List<Orgao> orgaoList = new ArrayList<Orgao>(100);
        try {
            PreparedStatement ps = conn.prepareStatement(sbSql.toString());
            int pos = 1;
            if (filter.hasCodigoSituacao()) {
                setInt(ps, pos++, filter.getCodigoSituacao());
            }
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                Orgao orgao = fromResultSet(rs);
                orgaoList.add(orgao);
            }
            close(rs);
        } catch (SQLException sqle) {
            throw new TransactionException("OrgaoDAO.findByFilter (" + sqle.getMessage() + ")");
        }
        return orgaoList;
    }

    public static void insert(Orgao orgao, Connection conn) throws TransactionException {

        StringBuffer sbSql = new StringBuffer();
        sbSql.append("INSERT INTO ORGAO   ");
        sbSql.append("     ( CD_ORGAO     ");
        sbSql.append("     , TX_NOME      ");
        sbSql.append("     , ID_SITUACAO  ");
        sbSql.append("     , TS_CADASTRO  ");
        sbSql.append(") VALUES (?,?,?,?)");
        try {
            PreparedStatement ps = conn.prepareStatement(sbSql.toString());
            int pos = 1;
            setInt(ps, pos++, orgao.getCodigo());
            setString(ps, pos++, orgao.getNome());
            setInt(ps, pos++, orgao.getSituacao().getCodigo());
            setTimestamp(ps, pos++, orgao.getDataCadastro());
            //
            ps.executeUpdate();
            close(ps);
        } catch (SQLException sqle) {
            throw new TransactionException("OrgaoDAO.insert (" + sqle.getMessage() + ")");
        }
    }

    public static void update(Orgao orgao, Connection conn) throws TransactionException {

        StringBuffer sbSql = new StringBuffer();
        sbSql.append("UPDATE ORGAO           ");
        sbSql.append("   SET TX_NOME     = ? ");
        sbSql.append("     , ID_SITUACAO = ? ");
        sbSql.append(" WHERE CD_ORGAO    = ? ");
        try {
            PreparedStatement ps = conn.prepareStatement(sbSql.toString());
            int pos = 1;
            setString(ps, pos++, orgao.getNome());
            setInt(ps, pos++, orgao.getSituacao().getCodigo());
            setInt(ps, pos++, orgao.getCodigo());
            //
            ps.executeUpdate();
            close(ps);
        } catch (SQLException sqle) {
            throw new TransactionException("OrgaoDAO.update (" + sqle.getMessage() + ")");
        }
    }

    public static void delete(Orgao orgao, Connection conn) throws TransactionException {

        StringBuffer sbSql = new StringBuffer();
        sbSql.append("DELETE FROM ORGAO  ");
        sbSql.append(" WHERE CD_ORGAO = ?");
        try {
            PreparedStatement ps = conn.prepareStatement(sbSql.toString());
            setInt(ps, 1, orgao.getCodigo());
            ps.executeUpdate();
            close(ps);
        } catch (SQLException sqle) {
            throw new TransactionException("OrgaoDAO.delete (" + sqle.getMessage() + ")");
        }
    }

    public static int getNextCodigo(Connection conn, int iRange, int eRange) throws TransactionException {

        try {
            StringBuffer sbSql = new StringBuffer();
            sbSql.append("SELECT MAX(CD_ORGAO) AS CD_MAX ");
            sbSql.append("  FROM ORGAO        ");
            sbSql.append(" WHERE CD_ORGAO > ? ");
            sbSql.append("   AND CD_ORGAO < ? ");

            PreparedStatement ps = conn.prepareStatement(sbSql.toString());
            setInt(ps, 1, iRange);
            setInt(ps, 2, eRange);
            ResultSet rs = ps.executeQuery();
            int max = 0;
            if (rs.next()) {
                max = rs.getInt("CD_MAX");
            }
            close(rs);
            return (max != 0 ? max : iRange) + 1;
        } catch (SQLException sqlEx) {
            throw new TransactionException(sqlEx);
        }
    }

    private static Orgao fromResultSet(ResultSet rs) throws SQLException {

        // ORGAO
        Orgao orgao = new Orgao();
        orgao.setCodigo(getInt(rs, "CD_ORGAO"));
        orgao.setNome(getString(rs, "TX_NOME"));
        orgao.setSituacao(Situacao.getSituacaoById(getByte(rs, "ID_SITUACAO")));
        orgao.setDataCadastro(getDateFromTimestamp(rs, "TS_CADASTRO"));
        //
        return orgao;
    }

}
